class AIAssistant:
    def __init__(self, id, name, type, version, online, score):
        self.id = id
        self.name = name
        self.type = type
        self.version = version
        self.online = online
        self.score = score

    def execute_task(self, task_content):
        if self.online:
            print(f"✅ 助手【{self.name}】开始执行任务：{task_content}")
        else:
            print(f"❌ 助手【{self.name}】当前离线，无法执行任务。")

    def __str__(self):
        status = "🟢在线" if self.online else "🔴离线"
        return f"ID：{self.id}，AI的名称：{self.name}，AI的类型：{self.type}，AI的版本：v{self.version}，状态：{status}，AI的评价：{self.score}"


class AIType(AIAssistant):
    def __init__(self, id, name, version, online, score):
        ai_type = self.get_type_by_name(name)
        super().__init__(id, name, ai_type, version, online, score)

    def get_type_by_name(self, name):
        type_mapping = {
            "DeepSeek": "数据分析助手",
            "腾讯元宝": "数据分析助手",
            "通义千问": "文本生成助手",
            "文心一言": "图片生成助手",
            "Kimi": "翻译助手",
            "小爱同学": "语音助手",
            "YOYO助理": "语音助手"
        }
        return type_mapping.get(name, "未知类型助手")


class DataAnalysisAssistant(AIType):
    def get_type_by_name(self, name):
        return "数据分析助手"


class TextGenerationAssistant(AIType):
    def get_type_by_name(self, name):
        return "文本生成助手"


class TranslationAssistant(AIType):
    def get_type_by_name(self, name):
        return "翻译助手"


class VoiceAssistant(AIType):
    def get_type_by_name(self, name):
        return "语音助手"


class AIManager:
    def __init__(self, max_size=12):
        self.max_size = max_size
        self.ai_assistants = []

    def add_ai(self, ai_assistant):
        if len(self.ai_assistants) >= self.max_size:
            print("❌ 达到最大助手容量，无法添加更多助手。")
            return False

        # 检查ID是否重复
        for ai in self.ai_assistants:
            if ai.id == ai_assistant.id:
                print(f"❌ ID【{ai_assistant.id}】已存在，添加失败！")
                return False

        self.ai_assistants.append(ai_assistant)
        print(f"✅ 助手【{ai_assistant.name}】添加成功！")
        return True

    def show_all(self):
        if not self.ai_assistants:
            print("当前没有AI助手，请先添加AI助手。")
            return

        print("=== AI助手列表 ===")
        for i, ai in enumerate(self.ai_assistants, 1):
            print(f"{i}. {ai}")

    def destroy_ai(self, ai_id):
        for i, ai in enumerate(self.ai_assistants):
            if ai.id == ai_id:
                removed_ai = self.ai_assistants.pop(i)
                print(f"✅ 助手【{removed_ai.name}】删除成功！")
                return True

        print(f"❌ 未找到ID【{ai_id}】的助手，删除失败！")
        return False

    def query_ai(self, ai_id):
        for ai in self.ai_assistants:
            if ai.id == ai_id:
                print(f"查询结果：{ai}")
                return ai

        print(f"❌ 未找到ID【{ai_id}】的助手")
        return None

    def start_ai(self, ai_id):
        ai = self.query_ai(ai_id)
        if ai:
            if ai.online:
                print(f"ℹ️  助手【{ai.name}】已在运行。")
            else:
                ai.online = True
                print(f"✅ 助手【{ai.name}】已启动，当前状态：在线")
            return True
        return False

    def stop_ai(self, ai_id):
        ai = self.query_ai(ai_id)
        if ai:
            if not ai.online:
                print(f"ℹ️  助手【{ai.name}】已停止。")
            else:
                ai.online = False
                print(f"✅ 助手【{ai.name}】已停止，当前状态：离线")
            return True
        return False

    def assign_task(self, ai_id, task_content):
        ai = self.query_ai(ai_id)
        if ai:
            ai.execute_task(task_content)
            return True
        return False

    def update_assistant(self, ai_id, prop_name, prop_value):
        ai = self.query_ai(ai_id)
        if not ai:
            return False

        prop_name = prop_name.lower()
        try:
            if prop_name == "name":
                ai.name = prop_value
            elif prop_name == "type":
                ai.type = prop_value
            elif prop_name == "version":
                ai.version = float(prop_value)
            elif prop_name == "online":
                ai.online = prop_value.lower() in ["1", "true", "yes", "在线"]
            elif prop_name == "score":
                score = int(prop_value)
                if 0 <= score <= 100:
                    ai.score = score
                else:
                    print("❌ 能力评分需在0-100之间，修改失败！")
                    return False
            else:
                print(f"❌ 未知属性名：{prop_name}")
                return False

            print(f"✅ 助手【{ai.name}】的属性【{prop_name}】已成功更新为【{prop_value}】")
            return True
        except ValueError as e:
            print(f"❌ 属性值格式错误：{e}")
            return False

    def show_system_stats(self):
        if not self.ai_assistants:
            print("系统统计信息：")
            print("总助手数: 0, 在线助手数: 0, 离线助手数: 0, 平均能力评分: 0.00")
            return

        total_count = len(self.ai_assistants)
        online_count = sum(1 for ai in self.ai_assistants if ai.online)
        total_score = sum(ai.score for ai in self.ai_assistants)
        avg_score = total_score / total_count

        print("系统统计信息：")
        print(f"总助手数: {total_count}")
        print(f"在线助手数: {online_count}")
        print(f"离线助手数: {total_count - online_count}")
        print(f"平均能力评分: {avg_score:.2f}")


def create_ai_assistant(name, ai_id, version, online, score):
    """根据名称创建对应的AI助手实例"""
    ai_creators = {
        "deepseek": lambda: DataAnalysisAssistant(ai_id, name, version, online, score),
        "deepseek": lambda: DataAnalysisAssistant(ai_id, name, version, online, score),
        "deepseek": lambda: DataAnalysisAssistant(ai_id, name, version, online, score),
        "腾讯元宝": lambda: DataAnalysisAssistant(ai_id, name, version, online, score),
        "通义千问": lambda: TextGenerationAssistant(ai_id, name, version, online, score),
        "文心一言": lambda: VoiceAssistant(ai_id, name, version, online, score),
        "kimi": lambda: TranslationAssistant(ai_id, name, version, online, score),
        "kimi": lambda: TranslationAssistant(ai_id, name, version, online, score),
        "kimi": lambda: TranslationAssistant(ai_id, name, version, online, score),
        "小爱同学": lambda: VoiceAssistant(ai_id, name, version, online, score),
        "yoyo助理": lambda: VoiceAssistant(ai_id, name, version, online, score),
        "yoyo助理": lambda: VoiceAssistant(ai_id, name, version, online, score),
    }

    creator = ai_creators.get(name.lower())
    if creator:
        return creator()
    else:
        # 如果不在预定义列表中，创建通用AI助手
        return AIAssistant(ai_id, name, "通用助手", version, online, score)


def initialize_default_ais(ai_manager):
    """初始化默认的AI助手"""
    default_ais = [
        VoiceAssistant(101, "小智", 1.2, True, 85),
        TextGenerationAssistant(102, "文小助", 2.0, True, 92),
        VoiceAssistant(103, "图灵", 1.5, False, 88),
        DataAnalysisAssistant(104, "数小析", 1.0, True, 79),
        TranslationAssistant(105, "翻译精灵", 2.1, False, 95),
    ]

    for ai in default_ais:
        ai_manager.add_ai(ai)


def main():
    ai_manager = AIManager()
    initialize_default_ais(ai_manager)

    while True:
        print("\n========== AI助手管理器 ==========")
        print("1. 查看所有AI助手列表")
        print("2. 根据ID查询助手详情")
        print("3. 添加新的AI助手")
        print("4. 删除AI助手（按ID）")
        print("5. 启动AI助手服务")
        print("6. 停止AI助手服务")
        print("7. 为AI助手分配任务")
        print("8. 显示系统统计信息")
        print("9. 根据ID修改助手信息")
        print("0. 退出系统")
        print("===================================")

        choice = input("请选择：").strip()

        if choice == "1":
            ai_manager.show_all()

        elif choice == "2":
            try:
                ai_id = int(input("请输入想查询的AI的ID: "))
                ai_manager.query_ai(ai_id)
            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "3":
            try:
                ai_id = int(input("填写AI的ID: "))
                name = input("填写AI的名称: ")
                version = float(input("填写AI的版本: "))
                online_input = input("填写AI是否在线（1代表在线，0代表不在线）: ")
                online = online_input == "1"
                score = int(input("填写AI的评分(1-100): "))

                if score < 0 or score > 100:
                    print("❌ 能力评分需在0-100之间，添加失败！")
                    continue

                ai_assistant = create_ai_assistant(name, ai_id, version, online, score)
                ai_manager.add_ai(ai_assistant)

            except ValueError:
                print("❌ 输入格式错误，请确保ID、版本和评分为数字！")

        elif choice == "4":
            try:
                ai_id = int(input("填写你需要删除的AI的ID: "))
                ai_manager.destroy_ai(ai_id)
            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "5":
            try:
                ai_id = int(input("请输入要启动的AI助手ID: "))
                ai_manager.start_ai(ai_id)
            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "6":
            try:
                ai_id = int(input("请输入要停止的AI助手ID: "))
                ai_manager.stop_ai(ai_id)
            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "7":
            try:
                ai_id = int(input("请输入目标AI助手ID: "))
                task_content = input("请输入任务内容: ").strip()
                ai_manager.assign_task(ai_id, task_content)
            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "8":
            ai_manager.show_system_stats()

        elif choice == "9":
            try:
                ai_id = int(input("请输入ID: "))
                print("可修改属性列表为：name, type, version, online, score")
                prop_input = input("请输入要修改的属性和值（用空格分割，如score 100）: ").strip().split(" ", 1)

                if len(prop_input) != 2:
                    print("❌ 输入格式错误！请按'属性名 值'格式输入。")
                    continue

                prop_name, prop_value = prop_input
                ai_manager.update_assistant(ai_id, prop_name, prop_value)

            except ValueError:
                print("❌ 请输入有效的数字ID！")

        elif choice == "0":
            print("欢迎下次使用AI助手管理器！")
            break

        else:
            print("❌ 无效的选择，请重新输入！")


if __name__ == "__main__":
    main()